package com.boot.security.server.controller.mffl.UserLogin;

import com.boot.security.server.dao.NoticeDao;
import com.boot.security.server.dao.PermissionDao;
import com.boot.security.server.dao.SysSmsDao;
import com.boot.security.server.dao.UserDao;
import com.boot.security.server.dao.mffl.MfflAdvertisingDao;
import com.boot.security.server.dao.mffl.MfflConsultationDao;
import com.boot.security.server.dao.mffl.MfflTypeDao;
import com.boot.security.server.dao.mffl.MfflUserDao;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.dto.Token;
import com.boot.security.server.dto.UserDto;
import com.boot.security.server.filter.TokenFilter;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.MfflAdvertising;
import com.boot.security.server.model.mffl.MfflType;
import com.boot.security.server.model.mffl.MfflUser;
import com.boot.security.server.model.mffl.SysSms;
import com.boot.security.server.model.mffl.Vo.LawyerUser;
import com.boot.security.server.model.mffl.Vo.LoginReturnVo;
import com.boot.security.server.model.mffl.Vo.MfflConsultationVo;
import com.boot.security.server.model.mffl.Vo.UserVo;
import com.boot.security.server.service.RoleService;
import com.boot.security.server.service.TokenService;
import com.boot.security.server.service.UserService;
import com.boot.security.server.service.impl.mffl.MfflUserlong.UserlongService;
import com.boot.security.server.utils.SmsUtils;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户登录
 *
 * @author Administrator
 */
@Api(tags = "登录/注册")
@RestController
@RequestMapping("/mffl")
public class UserLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SysSmsDao syssmsDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MfflUserDao mfflUserDao;

    @Autowired
    private MfflTypeDao mfflTypeDao;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private MfflConsultationDao mfflConsultationDao;

    //登录service
    @Autowired
    private UserlongService UserlongService;

    @Autowired
    private NoticeDao noticeDao;

    @Autowired
    private MfflAdvertisingDao mfflAdvertisingDao;

    //回调地址
    @Value("${Pay.NotifyIP}")
    private String NotifyIP;

    //默认图片地址
    @Value("${img.path}")
    private String path;


    @ApiOperation(value = "用户登录/注册")
    @PostMapping(value = "login")
    public ReturnBean<LoginReturnVo> login(@ApiParam(name = "phone", value = "手机号", required = true) @RequestParam String phone,
                                           @ApiParam(name = "code", value = "验证码", required = true) @RequestParam String code,
                                           @ApiParam(name = "identity", value = "0为用户/1为律师", required = true) @RequestParam String identity) {
        ReturnBean returnBean;

        //验证手机号
        if (SmsUtils.isnumber(phone)) {

            //验证用户是否夸端登录（用户用律师端登录，律师用用户端登录）
            Integer userIdentity = Integer.parseInt(identity);

            //获取验证码
            SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(phone));

            if (byPhone == null) {
                return new ReturnBean("101", "您还未发送验证码");
            }

            //判断验证码是否过期
            long startTime = byPhone.getSendtime().getTime();
            long endTime = System.currentTimeMillis();

            if ((endTime - startTime) > ((1000 * 60) * 10)) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("101");
                returnBean.setMessage("验证码过期");
            } else {
                //验证验证码
                if (byPhone.getCode().equals(code)) {
                    /**
                     * 不等于null为用户已存在，注册用户信息返回token
                     * 不等于注册用户返回用户信息与token
                     */
                    SysUser sysUser;
                    //获取用户信息
                    MfflUser MfflUser = mfflUserDao.getByPhone(phone);
                    if (MfflUser != null) {
                        //登录
                        if (MfflUser.getIdentity() != 0) {
                            returnBean = new ReturnBean();
                            returnBean.setErrCode("101");
                            returnBean.setMessage("当前登录账号为律师，请登录律师客户端");
                            return returnBean;
                        }
                        sysUser = userDao.getById((long) MfflUser.getUserid());
                        if (sysUser.getStatus() == 2) {
                            return new ReturnBean<>("101", "用户被锁定不可登录");
                        }
                    } else {
                        //注册,创建用户信息
                        String password = "123456";
                        String username = getStringRandom(5);
                        Date date = new Date();
                        UserDto userDto = new UserDto();
                        List<Long> dto = new ArrayList<Long>();
                        dto.add(roleService.getrole(Integer.valueOf(identity) == 1 ? "lawyer" : "client").getId());
                        userDto.setRoleIds(dto);
                        userDto.setUsername(phone);
                        userDto.setPassword(password);
                        userDto.setNickname(username);
                        userDto.setHeadImgUrl(path);
                        userDto.setPhone(phone);
                        userDto.setSex(1);
                        sysUser = userService.saveUser(userDto);

                        MfflUser mfflUser = new MfflUser();
                        mfflUser.setUserid(sysUser.getId().intValue());
                        mfflUser.setRealname("");
                        mfflUser.setIdnumber("");
                        mfflUser.setOpenid("");
                        mfflUser.setUnionid("");
                        mfflUser.setAreaCode("");
                        mfflUser.setRegisterMethod("手机号");
                        mfflUser.setAreaName("");
                        mfflUser.setComid(0);
                        mfflUser.setThirdlevel("");
                        mfflUser.setLevel(0);
                        mfflUser.setStartWorkTime(date);
                        mfflUser.setWorkCode("");
                        mfflUser.setLawfirm("");
                        mfflUser.setField("");
                        mfflUser.setServerNumber(0);
                        mfflUser.setRating("100");
                        mfflUser.setWorkBootImage("");
                        mfflUser.setEducation("");
                        mfflUser.setContent("");
                        mfflUser.setIntegral(0);
                        mfflUser.setGradeIntegral("");
                        mfflUser.setSearchLike("");
                        mfflUser.setIdnumberImage("");
                        mfflUser.setCreateTime(date);
                        mfflUser.setUpdateTime(date);
                        mfflUser.setIdentity(Integer.valueOf(identity) == 1 ? 1 : 0);
                        mfflUser.setDeleteTime(date);
                        mfflUser.setDeleteState(1);
                        mfflUser.setLawyerInspect(0);
                        mfflUser.setMoney(ProjectUtil.addition(0.0,0.0));
                        mfflUser.setSecondusername(ProjectUtil.getRandomString(12));//随机用户名
                        mfflUserDao.save(mfflUser);
                    }

                    //配置用户信息到组成token的结构中
                    MfflUser MfflUser1 = mfflUserDao.getByPhone(phone);
                    LoginUser loginUser = new LoginUser();
                    loginUser.setPermissions(permissionDao.listByUserId(sysUser.getId()));
                    loginUser.setId(sysUser.getId());
                    loginUser.setUsername(sysUser.getUsername());
                    loginUser.setPassword("$10$.QfHB7vQwZ/DGiYo.cckJeRCpk5.bMnFCrG6DmtCCMwu0vnib.RrG");
                    loginUser.setNickname(sysUser.getNickname());
                    loginUser.setHeadImgUrl(sysUser.getHeadImgUrl());
                    loginUser.setCreateTime(sysUser.getCreateTime());
                    loginUser.setUpdateTime(sysUser.getUpdateTime());

                    //获取token,配置给前端返回的信息
                    Token token = tokenService.saveToken(loginUser);
//                    HashMap<String, Object> map = new HashMap<String, Object>();
//                    map.put("token", token.getToken());
//                    map.put("userInfo", mfflUserDao.getUserInfoSimple(sysUser.getId().intValue()));
//                    map.put("sys_id", sysUser.getId());
//                    map.put("nickname", sysUser.getNickname());
//                    map.put("sex", sysUser.getSex());
//                    map.put("phone", sysUser.getPhone());
//                    map.put("loginTime", token.getLoginTime());
//                    map.put("username", sysUser.getUsername());
//                    map.put("email", sysUser.getEmail());
//                    map.put("identity", MfflUser1.getIdentity());
//                    map.put("idnumber", MfflUser1.getIdnumber());
//                    map.put("headImgUrl", sysUser.getHeadImgUrl());
//                    map.put("realname", MfflUser1.getRealname());
//                    map.put("register_method", MfflUser1.getRegisterMethod());
                    LoginReturnVo loginReturnVo = new LoginReturnVo();
                    loginReturnVo.setToken(token.getToken());
                    loginReturnVo.setUserInfo(mfflUserDao.getUserInfoSimple(sysUser.getId().intValue()));
                    loginReturnVo.setSys_id(sysUser.getId());
                    loginReturnVo.setNickanme(sysUser.getNickname());
                    loginReturnVo.setPhone(sysUser.getPhone());
                    loginReturnVo.setLoginTime(token.getLoginTime());
                    loginReturnVo.setUsername(sysUser.getUsername());
                    loginReturnVo.setEmail(sysUser.getEmail());
                    loginReturnVo.setIdentity(MfflUser1.getIdentity());
                    loginReturnVo.setIdnumber(MfflUser1.getIdnumber());
                    loginReturnVo.setHeadImgUrl(sysUser.getHeadImgUrl());
                    loginReturnVo.setRealname(MfflUser1.getRealname());
                    loginReturnVo.setRegisterMethod(MfflUser1.getRegisterMethod());
                    returnBean = new ReturnBean();
                    returnBean.setDatas(loginReturnVo);
                } else {
                    returnBean = new ReturnBean();
                    returnBean.setErrCode("103");
                    returnBean.setMessage("验证码不正确");
                }
            }
        } else {
            returnBean = new ReturnBean();
            returnBean.setErrCode("101");
            returnBean.setMessage("手机号不正确");
        }
        return returnBean;
    }


    @ApiOperation(value = "律师注册")
    @PostMapping(value = "lawyerreg")
    public ReturnBean<LoginReturnVo> LawyerReg(@ApiParam(name = "phone", value = "手机号", required = true) @RequestParam String phone,
                                               @ApiParam(name = "code", value = "验证码", required = true) @RequestParam String code,
                                               @ApiParam(name = "pass", value = "密码（律师专用）", required = true) @RequestParam String pass) {
        ReturnBean returnBean;

        if (StringUtils.isEmpty(phone)) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("201");
            returnBean.setMessage("手机号不能为空");
            return returnBean;
        }

        if (StringUtils.isEmpty(code)) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("201");
            returnBean.setMessage("验证码不能为空");
            return returnBean;
        }

        if (StringUtils.isEmpty(pass)) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("201");
            returnBean.setMessage("密码不能为空");
            return returnBean;
        }

        if (pass.length() < 6) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("201");
            returnBean.setMessage("密码不能小于6位");
            return returnBean;
        }

        //验证手机号
        if (SmsUtils.isnumber(phone)) {
            //获取用户信息
            MfflUser MfflUser = mfflUserDao.getByPhone(phone);
            if (MfflUser != null) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("201");
                returnBean.setMessage("用户已存在");
                return returnBean;
            }
            //获取验证码
            SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(phone));

            if (byPhone == null) {
                return new ReturnBean("101", "您还未发送验证码");
            }

            //判断验证码是否过期
            long startTime = byPhone.getSendtime().getTime();
            long endTime = System.currentTimeMillis();

            if ((endTime - startTime) > ((1000 * 60) * 10)) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("101");
                returnBean.setMessage("验证码过期");
            } else {
                //验证验证码
                if (byPhone.getCode().equals(code)) {
                    /**
                     * 不等于null为用户已存在，注册用户信息返回token
                     * 不等于注册用户返回用户信息与token
                     */
                    if (MfflUser != null) {
                        //登录
                        returnBean = new ReturnBean();
                        returnBean.setErrCode("101");
                        returnBean.setMessage("该用户已存在");
                        return returnBean;
                    }
                    //注册,创建用户信息
                    String password = pass;
                    String username = getStringRandom(5);
                    Date date = new Date();
                    UserDto userDto = new UserDto();
                    List<Long> dto = new ArrayList<Long>();
                    dto.add(roleService.getrole("lawyer").getId());
                    userDto.setRoleIds(dto);
                    userDto.setUsername(phone);
                    userDto.setPassword(password);
                    userDto.setNickname(username);
                    userDto.setHeadImgUrl(path);
                    userDto.setPhone(phone);
                    userDto.setSex(1);
                    SysUser sysUser = userService.saveUser(userDto);

                    MfflUser mfflUser = new MfflUser();
                    mfflUser.setUserid(sysUser.getId().intValue());
                    mfflUser.setRealname("");
                    mfflUser.setIdnumber("");
                    mfflUser.setOpenid("");
                    mfflUser.setUnionid("");
                    mfflUser.setAreaCode("");
                    mfflUser.setRegisterMethod("手机号");
                    mfflUser.setAreaName("");
                    mfflUser.setComid(0);
                    mfflUser.setThirdlevel("");
                    mfflUser.setLevel(0);
                    mfflUser.setStartWorkTime(date);
                    mfflUser.setWorkCode("");
                    mfflUser.setLawfirm("");
                    mfflUser.setField("");
                    mfflUser.setServerNumber(0);
                    mfflUser.setRating("100");
                    mfflUser.setWorkBootImage("");
                    mfflUser.setEducation("");
                    mfflUser.setContent("");
                    mfflUser.setIntegral(0);
                    mfflUser.setGradeIntegral("");
                    mfflUser.setSearchLike("");
                    mfflUser.setCreateTime(date);
                    mfflUser.setUpdateTime(date);
                    mfflUser.setIdentity(1);
                    mfflUser.setDeleteTime(date);
                    mfflUser.setDeleteState(1);
                    mfflUser.setLawyerInspect(0);
                    mfflUser.setMoney(ProjectUtil.addition(0.0,0.0));
                    mfflUser.setIdnumberImage("");
                    mfflUser.setSecondusername(ProjectUtil.getRandomString(12));//随机用户名
                    mfflUserDao.save(mfflUser);


                    //配置用户信息到组成token的结构中
                    MfflUser MfflUser1 = mfflUserDao.getByPhone(phone);
                    LoginUser loginUser = new LoginUser();
                    loginUser.setPermissions(permissionDao.listByUserId(sysUser.getId()));
                    loginUser.setId(sysUser.getId());
                    loginUser.setUsername(sysUser.getUsername());
//                    loginUser.setPassword("$10$.QfHB7vQwZ/DGiYo.cckJeRCpk5.bMnFCrG6DmtCCMwu0vnib.RrG");
                    loginUser.setNickname(sysUser.getNickname());
                    loginUser.setHeadImgUrl(sysUser.getHeadImgUrl());
                    loginUser.setCreateTime(sysUser.getCreateTime());
                    loginUser.setUpdateTime(sysUser.getUpdateTime());

                    //获取token,配置给前端返回的信息
                    Token token = tokenService.saveToken(loginUser);
//                    HashMap<String, Object> map = new HashMap<String, Object>();
//                    map.put("token", token.getToken());
//                    map.put("userInfo", mfflUserDao.getUserInfoSimple(sysUser.getId().intValue()));
//                    map.put("sys_id", sysUser.getId());
//                    map.put("nickname", sysUser.getNickname());
//                    map.put("phone", sysUser.getPhone());
//                    map.put("loginTime", token.getLoginTime());
//                    map.put("username", sysUser.getUsername());
//                    map.put("email", sysUser.getEmail());
//                    map.put("identity", MfflUser1.getIdentity());
//                    map.put("idnumber", MfflUser1.getIdnumber());
//                    map.put("headImgUrl", sysUser.getHeadImgUrl());
//                    map.put("realname", MfflUser1.getRealname());
//                    map.put("register_method", MfflUser1.getRegisterMethod());
                    LoginReturnVo loginReturnVo = new LoginReturnVo();
                    loginReturnVo.setToken(token.getToken());
                    loginReturnVo.setUserInfo(mfflUserDao.getUserInfoSimple(sysUser.getId().intValue()));
                    loginReturnVo.setSys_id(sysUser.getId());
                    loginReturnVo.setNickanme(sysUser.getNickname());
                    loginReturnVo.setPhone(sysUser.getPhone());
                    loginReturnVo.setLoginTime(token.getLoginTime());
                    loginReturnVo.setUsername(sysUser.getUsername());
                    loginReturnVo.setEmail(sysUser.getEmail());
                    loginReturnVo.setIdentity(MfflUser1.getIdentity());
                    loginReturnVo.setIdnumber(MfflUser1.getIdnumber());
                    loginReturnVo.setHeadImgUrl(sysUser.getHeadImgUrl());
                    loginReturnVo.setRealname(MfflUser1.getRealname());
                    loginReturnVo.setRegisterMethod(MfflUser1.getRegisterMethod());
                    returnBean = new ReturnBean();
                    returnBean.setDatas(loginReturnVo);
                } else {
                    returnBean = new ReturnBean();
                    returnBean.setErrCode("103");
                    returnBean.setMessage("验证码不正确");
                }
            }
        } else {
            returnBean = new ReturnBean();
            returnBean.setErrCode("101");
            returnBean.setMessage("手机号不正确");
        }
        return returnBean;
    }


    @ApiOperation(value = "律师登录")
    @PostMapping(value = "lawyerlogin")
    public ReturnBean<LoginReturnVo> loginLawyerReg(@ApiParam(name = "phone", value = "手机号", required = true) @RequestParam String phone,
                                                    @ApiParam(name = "code", value = "验证码", required = false) @RequestParam(required = false) String code,
                                                    @ApiParam(name = "pass", value = "密码（律师专用）", required = false) @RequestParam(required = false) String pass,
                                                    @ApiParam(name = "type", value = "0为短信登录1为密码登录", required = true) @RequestParam Integer type) {
        ReturnBean returnBean;


        if (StringUtils.isEmpty(phone)) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("201");
            returnBean.setMessage("手机号不能为空");
            return returnBean;
        }

        //验证手机号
        if (!SmsUtils.isnumber(phone)) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("101");
            returnBean.setMessage("手机号不正确");
        }

        //获取用户信息
        MfflUser MfflUser = mfflUserDao.getByPhone(phone);
        if (MfflUser == null) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("101");
            returnBean.setMessage("用户不存在");
            return returnBean;
        }
        //登录
        if (MfflUser.getIdentity() != 1) {
            returnBean = new ReturnBean();
            returnBean.setErrCode("101");
            returnBean.setMessage("当前登录账号为用户，请登录用户客户端");
            return returnBean;
        }

        SysUser sysUser = userDao.getById((long) MfflUser.getUserid());
        if (sysUser.getStatus() == 2) {
            return new ReturnBean<>("101", "用户被锁定不可登录");
        }
        //密码登录
        if (type == 0) {
            //验证码为空
            if (StringUtils.isEmpty(code)) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("101");
                returnBean.setMessage("验证码不能为空");
                return returnBean;
            } else {
                //判断验证码是否过期
                SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(phone));
                if(StringUtils.isEmpty(byPhone)){
                    returnBean = new ReturnBean();
                    returnBean.setErrCode("101");
                    returnBean.setMessage("还未发送验证码");
                    return returnBean;
                }
                long startTime = byPhone.getSendtime().getTime();
                long endTime = System.currentTimeMillis();

                if ((endTime - startTime) > ((1000 * 60) * 10)) {
                    returnBean = new ReturnBean();
                    returnBean.setErrCode("101");
                    returnBean.setMessage("验证码过期");
                    return returnBean;
                }
                if (!byPhone.getCode().equals(code)) {
                    returnBean = new ReturnBean();
                    returnBean.setErrCode("101");
                    returnBean.setMessage("验证不正确");
                    return returnBean;
                }
            }
        } else {
            //验证码登录
            if (StringUtils.isEmpty(pass)) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("101");
                returnBean.setMessage("密码不能为空");
                return returnBean;
            }

            if (!passwordEncoder.matches(pass, sysUser.getPassword())) {
                returnBean = new ReturnBean();
                returnBean.setErrCode("101");
                returnBean.setMessage("密码不正确");
                return returnBean;
            }
        }

        //配置用户信息到组成token的结构中
        MfflUser MfflUser1 = mfflUserDao.getByPhone(phone);
        LoginUser loginUser = new LoginUser();
        loginUser.setPermissions(permissionDao.listByUserId(sysUser.getId()));
        loginUser.setId(sysUser.getId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setPassword("$10$.QfHB7vQwZ/DGiYo.cckJeRCpk5.bMnFCrG6DmtCCMwu0vnib.RrG");
        loginUser.setNickname(sysUser.getNickname());
        loginUser.setHeadImgUrl(sysUser.getHeadImgUrl());
        loginUser.setCreateTime(sysUser.getCreateTime());
        loginUser.setUpdateTime(sysUser.getUpdateTime());

        //获取token,配置给前端返回的信息
        Token token = tokenService.saveToken(loginUser);
        LoginReturnVo loginReturnVo = new LoginReturnVo();
        loginReturnVo.setToken(token.getToken());
        loginReturnVo.setUserInfo(mfflUserDao.getUserInfoSimple(sysUser.getId().intValue()));
        loginReturnVo.setSys_id(sysUser.getId());
        loginReturnVo.setNickanme(sysUser.getNickname());
        loginReturnVo.setPhone(sysUser.getPhone());
        loginReturnVo.setLoginTime(token.getLoginTime());
        loginReturnVo.setUsername(sysUser.getUsername());
        loginReturnVo.setEmail(sysUser.getEmail());
        loginReturnVo.setIdentity(MfflUser1.getIdentity());
        loginReturnVo.setIdnumber(MfflUser1.getIdnumber());
        loginReturnVo.setHeadImgUrl(sysUser.getHeadImgUrl());
        loginReturnVo.setRealname(MfflUser1.getRealname());
        loginReturnVo.setRegisterMethod(MfflUser1.getRegisterMethod());
        returnBean = new ReturnBean();
        returnBean.setDatas(loginReturnVo);
        return returnBean;
    }


    @PostMapping("/updateJPush")
    @ApiOperation("登录-修改极光推送标识")
    public ReturnBean updateJPush(@ApiParam(value = "极光推送标识", name = "jpush", required = true) @RequestParam String jpush) {

        if (StringUtils.isEmpty(jpush)) {
            return new ReturnBean("201", "标识不可为空");
        }

        SysUser sysUser = UserUtil.getLoginUser();
        int status = this.mfflUserDao.updateJPush(jpush, sysUser.getId());
        if (status == 0) {
            return new ReturnBean("201", "修改失败");
        }
        return new ReturnBean();
    }


    @GetMapping("/index")
    @ApiOperation("登录-用户端首页")
    public ReturnBean index(@ApiParam(value = "首页律师类型主键id,传 0 是推荐 ", name = "type", required = true) @RequestParam Integer type,
                            @ApiParam(value = "首页律师显示个数 ", name = "count", required = true) @RequestParam Integer count,
                            HttpServletRequest request) {

        SysUser sysUser = UserUtil.getLoginUser();
        SysUser user = userDao.getById(sysUser.getId());
        if (user.getStatus() == 2) {
            String token = TokenFilter.getToken(request);
            if (tokenService.deleteToken(token)) {
                return new ReturnBean("201", "用户被锁定");
            }

        }

        Map<String, Object> map = new HashMap<>();
        List<MfflType> mfflTypeList = this.mfflTypeDao.getLawyerType();
        map.put("lawyerType", mfflTypeList);
        List<LawyerUser> lawyerUserList = new ArrayList<>();
        if (type == 0) {
            lawyerUserList = this.mfflUserDao.getUserListByTypeRecommend(count);
        } else {
            lawyerUserList = this.mfflUserDao.getUserListByType(type, count);
        }

        map.put("lawyerList", getFieldList(lawyerUserList));

        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(map);
        return returnBean;
    }

    @GetMapping("/lawyerIndex")
    @ApiOperation("登录-律师端首页(推荐案例)")
    public ReturnBean<MfflConsultationVo> lawyerIndex(@ApiParam(value = "首页推荐案例分类id,传 0 是推荐 ", name = "type", required = true) @RequestParam Integer type,
                                                      @ApiParam(value = "首页推荐案例显示个数 ", name = "count", required = true) @RequestParam Integer count,
                                                      HttpServletRequest request) {

        SysUser sysUser = UserUtil.getLoginUser();
        SysUser user = userDao.getById(sysUser.getId());
        if (user.getStatus() == 2) {
            String token = TokenFilter.getToken(request);
            if (tokenService.deleteToken(token)) {
                return new ReturnBean("201", "用户被锁定");
            }
        }
        List<MfflConsultationVo> mfflConsultationList = new ArrayList<>();
        if (type == 0 || type == null) {
            mfflConsultationList = this.mfflConsultationDao.getConsultationByTypeRecommend(count);
        } else {
            mfflConsultationList = this.mfflConsultationDao.getConsultationByType(type, count);
        }
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflConsultationList);
        return returnBean;
    }

    @PostMapping(value = "/updateSysUser")
    @ApiOperation("个人中心-修改个人信息")
    public ReturnBean updateSysUser(@ApiParam(value = "头像地址，传(*_min.png)的图片地址", name = "headImgUrl") @RequestParam(required = false) String headImgUrl,
                                    @ApiParam(value = "昵称", name = "nickname") @RequestParam(required = false) String nickname,
                                    @ApiParam(value = "手机号", name = "phone") @RequestParam(required = false) String phone,
                                    @ApiParam(value = "验证码(改手机号需要传该字段)", name = "code") @RequestParam(required = false) String code) {

        SysUser sysUser = UserUtil.getLoginUser();
        if (!StringUtils.isEmpty(headImgUrl)) {
            sysUser.setHeadImgUrl(headImgUrl);
        }
        if (!StringUtils.isEmpty(nickname)) {
            sysUser.setNickname(nickname);
        }
        if (!StringUtils.isEmpty(phone)) {
            MfflUser mfflUserByPhone = mfflUserDao.getByPhone(phone);
            if (mfflUserByPhone != null) {
                return new ReturnBean("201", "手机号不可重复");
            }

            if (phone.length() != 11) {
                return new ReturnBean("201", "不是手机号");
            }
            //获取验证码
            SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(phone));
            if (byPhone == null) {
                return new ReturnBean("101", "您还未发送验证码");
            }
            long startTime = byPhone.getSendtime().getTime();
            long endTime = System.currentTimeMillis();
            if ((endTime - startTime) > ((1000 * 60) * 10)) {
                return new ReturnBean("201", "验证码过期");
            }
            if (byPhone.getCode().equals(code)) {
                sysUser.setPhone(phone);
                sysUser.setUsername(phone);
            } else {
                return new ReturnBean("201", "验证码错误");
            }


        }

        int status = this.userDao.update(sysUser);
        if (status == 0) {
            return new ReturnBean("201", "修改失败");
        }
        UserVo userVo = this.userDao.getUserVoById(sysUser.getId());
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(userVo);
        return returnBean;
    }


    //获取律师分类 汉字
    public List<LawyerUser> getFieldList(List<LawyerUser> lawyerUserList) {
        for (LawyerUser l : lawyerUserList) {
            if (!StringUtils.isEmpty(l.getField())) {
                String[] typeGroup = l.getField().split(",");
                String fields = "";
                for (String field : typeGroup) {
                    if (field != null && !"".equals(field)) {
                        fields += field + ",";
                    }
                }
                l.setPassword("");
                l.setFieldList(this.mfflTypeDao.getLawyerTypeListById(fields.substring(0, fields.length() - 1)));
            }
        }
        return lawyerUserList;
    }


    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {
        String name = "mffl";
        for (int i = 0; i < length; i++) {
            name += String.valueOf((int) (1 + Math.random() * 10));
        }
        return name;
    }


    /**
     * 微信登录
     *
     * @return
     */
    @PostMapping(value = "wechatlogin")
    @ApiOperation(value = "【微信】登录  注：如果当前用户未绑定手机号，请使用 【微信】微信openid与手机号绑定 进行登录")
    public ReturnBean<LoginReturnVo> wechatlogin(@ApiParam(name = "openid", value = "openid", required = true) @RequestParam String openid,
                                                 @ApiParam(name = "access_token", value = "access_token", required = true) @RequestParam String access_token) {
        if (StringUtils.isEmpty(openid)) {
            return new ReturnBean("201", "openid不能为空");
        }

        if (StringUtils.isEmpty(access_token)) {
            return new ReturnBean("201", "access_token不能为空");
        }
        return UserlongService.wechatlogin(openid, access_token);
    }


    /**
     * 微信openid绑定手机号
     *
     * @return
     */
    @PostMapping(value = "openidandphonebind")
    @ApiOperation(value = "【微信】微信openid与手机号绑定")
    public ReturnBean<LoginReturnVo> openidAndphoneBind(@ApiParam(name = "openid", value = "openid", required = true) @RequestParam String openid,
                                                        @ApiParam(name = "access_token", value = "access_token", required = true) @RequestParam String access_token,
                                                        @ApiParam(name = "phone", value = "手机号", required = true) @RequestParam String phone,
                                                        @ApiParam(name = "code", value = "手机短信验证码", required = true) @RequestParam String code) {
        if (StringUtils.isEmpty(openid)) {
            return new ReturnBean("201", "openid不能为空");
        }

        if (StringUtils.isEmpty(phone)) {
            return new ReturnBean("201", "手机号，不能为空");
        }

        if (StringUtils.isEmpty(access_token)) {
            return new ReturnBean("201", "access_token不能为空");
        }

        if (StringUtils.isEmpty(code)) {
            return new ReturnBean("201", "手机短信验证码，不能为空");
        }

        //判断验证码是否过期
        SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(phone));
        if (byPhone == null) {
            return new ReturnBean("101", "您还未发送验证码");
        }

        long startTime = byPhone.getSendtime().getTime();
        long endTime = System.currentTimeMillis();

        if ((endTime - startTime) > ((1000 * 60) * 10)) {
            return new ReturnBean("101", "验证码过期");
        } else {
            if (!byPhone.getCode().equals(code)) {
                return new ReturnBean("101", "验证码不正确");
            }
        }
        return UserlongService.openidAndphoneBind(openid, phone, access_token);
    }


    /**
     * 微信openid解除绑定手机号
     *
     * @return
     */
    @PostMapping(value = "openidandphoneunbind")
    @ApiOperation(value = "【微信】微信openid与手机号解除绑定")
    public ReturnBean<LoginReturnVo> openidAndphoneUnbind(HttpServletRequest request,
                                                          @ApiParam(name = "openid", value = "openid", required = true) @RequestParam String openid,
                                                          @ApiParam(name = "access_token", value = "access_token", required = true) @RequestParam String access_token) {
        if (StringUtils.isEmpty(openid)) {
            return new ReturnBean("201", "openid，不能为空");
        }
        if (StringUtils.isEmpty(access_token)) {
            return new ReturnBean("201", "access_token，不能为空");
        }


        return UserlongService.openidAndphoneUnbind(request, openid, access_token);
    }


    @GetMapping(value = "Cancellation")
    @ApiOperation(value = "注销(退出登录)")
    public ReturnBean Cancellation(HttpServletRequest request) {
        boolean b = UserlongService.deleteToken(request);
        if (b) {
            return new ReturnBean();
        } else {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("105");
            return returnBean;
        }
    }

    @GetMapping("/getArticle")
    @ApiOperation("获取文章（用户协议）")
    public ReturnBean getArticle(@ApiParam(value = "获取文章 用户协议：1 ", name = "id", required = true) @RequestParam Long id) {
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(this.noticeDao.getById(id));
        return returnBean;
    }

    @PutMapping("/changepassword")
    @ApiOperation("律师修改密码")
    public ReturnBean ChangePassword(@ApiParam(name = "newpassword", value = "新密码", required = true) @RequestParam String newpassword,
                                     @ApiParam(name = "confirmnewpassword", value = "确认新密码", required = true) @RequestParam String confirmnewpassword,
                                     @ApiParam(name = "userphone", value = "用户手机号", required = true) @RequestParam String userphone,
                                     @ApiParam(name = "code", value = "验证码", required = true) @RequestParam String code) {
        if (StringUtils.isEmpty(newpassword)) {
            return new ReturnBean("201", "新密码，不能为空");
        }
        if (StringUtils.isEmpty(confirmnewpassword)) {
            return new ReturnBean("201", "确认新密码，不能为空");
        }
        if (StringUtils.isEmpty(userphone)) {
            return new ReturnBean("201", "用户手机号，不能为空");
        }
        if (StringUtils.isEmpty(code)) {
            return new ReturnBean("201", "验证码，不能为空");
        }
        if (!newpassword.equals(confirmnewpassword)) {
            return new ReturnBean("201", "两次密码不一致");
        }

        //获取验证码
        SysSms byPhone = syssmsDao.getByPhone(Long.parseLong(userphone));
        if (byPhone == null) {
            return new ReturnBean("101", "您还未发送验证码");
        }
        long startTime = byPhone.getSendtime().getTime();
        long endTime = System.currentTimeMillis();
        if ((endTime - startTime) > ((1000 * 60) * 10)) {
            return new ReturnBean("201", "验证码过期");
        }
        if (!byPhone.getCode().equals(code)) {
            return new ReturnBean("201", "验证码错误");
        }
        return UserlongService.ChangePassword(newpassword, confirmnewpassword, userphone, code);
    }


    @GetMapping("/getUserInfo")
    @ApiOperation("获取用户信息")
    public ReturnBean<MfflUser> getUserInfo() {
        SysUser sysUser = UserUtil.getLoginUser();
        MfflUser mfflUser = this.mfflUserDao.getUserInfoAll(sysUser.getId().intValue());
        mfflUser.setPassword("");
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(mfflUser);
        return returnBean;
    }


    @GetMapping("/getAdvertising")
    @ApiOperation("获取广告")
    public ReturnBean<MfflAdvertising> getAdvertising(
            @ApiParam(name = "size", value = "广告条数 空默认10条") @RequestParam(required = false) Integer size,
            @ApiParam(name = "advertisingType", value = "广告类型 0 用户 1 律师") @RequestParam Integer advertisingType) {
        List<MfflAdvertising> list = new ArrayList<>();

        if (size == null) {
            Integer count = 10;
            list = this.mfflAdvertisingDao.getAdvertisingList(count,advertisingType);
        } else {
            list = this.mfflAdvertisingDao.getAdvertisingList(size,advertisingType);
        }

        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(list);
        return returnBean;
    }

}
